package my.ts.code.net;

import my.ts.code.KLog;

public class InputThread extends Thread {
	public boolean quit = false;
	private SocketHandler socket;
	private InComingListener listener;

	//
	// Event listener
	public InputThread(SocketHandler socket) {
		this.socket = socket;
		this.start();
		KLog.log("------ Started input thread");
	}

	public void setListener(InComingListener l) {
		this.listener = l;
	}

	public void run() {
		while (!quit) {
			Thread.yield();
			try {
				 KLog.log("check for icomming message");
				process(socket.receivedMessage());
				Thread.sleep(50);
			} catch (Exception io) {
				io.printStackTrace();
				quit = true;
				try {
					// ((BaseScreen)Beme.engine.getCurrentScreen()).showDisconnectMessage();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} finally {
				// closeNetwork();
			}
		}
	}

	public void stopThread() {
		quit = true;
	}

	private void process(String str) throws Exception {
		System.out.println("PROCESS");
		if (str == null) {
			quit = true;
			KLog.log("QUIT vi ko doc duoc packet");
			return;
		} else {
			System.out.println("STR="+str);
			listener.dispatch(str);
		}
		//
	}

}
